package net.chemistry;

import java.io.Serializable;
import java.util.Arrays;

public class Bond implements Serializable
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5812813498382086574L;

	private boolean isionic;
	
	private int numbonds;
	
	private final Atom[] atomsinvolved = new Atom[2];
	
	public Bond(Atom atom0, Atom atom1)
	{
		this(atom0, atom1, 1, false);
	}
	
	public Bond(Atom atom0, Atom atom1, int num)
	{
		this(atom0, atom1, num, false);
	}
	
	public Bond(Atom atom0, Atom atom1, int numbonds, boolean ionic)
	{
		if (atom0 == atom1)
		{
			throw new IllegalArgumentException("Cannot bond an atom to itself.");
		}
		
		this.isionic = ionic;
		this.numbonds = numbonds;
		
		atomsinvolved[0] = atom0;
		atomsinvolved[1] = atom1;
	}
	
	public String toString()
	{
		return (isionic ? "ionic" : "covalent") + " bond of " + Arrays.toString(atomsinvolved) + " @" + Integer.toHexString(this.hashCode());
	} 
	
 	public boolean isIonic()
	{
		return isionic;
	}
	
 	public boolean hasAtom(Atom atom)
 	{
 		return ((Object)atom).equals(atomsinvolved[0]) || atom.equals(atomsinvolved[1]);
 	}
 	
	public int getBondLevel()
	{
		return numbonds;
	}
	
	public Atom getOther(Atom thisAtom)
	{
		boolean a0 = thisAtom == atomsinvolved[0];
		boolean a1 = thisAtom == atomsinvolved[1];
		
		if (a0 == a1)
		{
			throw new IllegalArgumentException(a0 ? "Impossible bond state: Atom is bonded to itself." :
													"Bond does not contain the thisAtom.");
		}
		
		return a0 ? atomsinvolved[1] : atomsinvolved[0];
	}
	
	public Atom[] getInvolvedAtoms()
	{
		return atomsinvolved.clone();
	}
}
